package com.senlingspace.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.senlingspace.common.core.domain.AjaxResult;
import com.senlingspace.common.enums.OrderSource;
import com.senlingspace.common.exception.ServiceException;
import com.senlingspace.common.utils.DateUtils;
import com.senlingspace.common.utils.NumberGenerator;
import com.senlingspace.common.utils.PageUtils;
import com.senlingspace.system.domain.Project;
import com.senlingspace.system.domain.SlkjCopyright;
import com.senlingspace.system.domain.dto.ShopProjectDTO;
import com.senlingspace.system.domain.vo.PosProjectVo;
import com.senlingspace.system.domain.vo.ProjectDetailVo;
import com.senlingspace.system.mapper.ProjectMapper;
import com.senlingspace.system.mapper.SlkjCopyrightMapper;
import com.senlingspace.system.mapper.SlkjShopProjectFzMapper;
import com.senlingspace.system.service.IProjectService;
import com.senlingspace.system.service.ISlkjFareSchemeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目Service业务层处理
 *
 * @author SenlingSpace
 * @date 2024-06-26
 */
@Slf4j
@Service
public class ProjectServiceImpl implements IProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private SlkjCopyrightMapper slkjCopyrightMapper;

    @Autowired
    private SlkjShopProjectFzMapper slkjShopProjectFzMapper;

    @Autowired
    private ISlkjFareSchemeService iSlkjFareSchemeService;


    public ShopProjectDTO getShopAndProjectDetails(Long shopId) {

// 提取 categories 中的 miniAppPrice 并找出最大值和最小值
        BigDecimal maxPrice = null;
        BigDecimal minPrice = null;

        ShopProjectDTO shopProjectDTO = projectMapper.getShopAndProjectDetails(shopId);

        if (shopProjectDTO == null) {
            return null;
        }

//        获取价格的最大值和最小值
        AjaxResult projects = iSlkjFareSchemeService.projects(shopId, OrderSource.MINI_PROGRAM.getCode());
        log.info("获取小程序价格信息：{}",JSON.toJSONString(projects));
        Integer code = (Integer) projects.get("code");
        if (200 != code ) {
            log.error("获取小程序价格信息失败：{}", JSON.toJSONString(projects));
            throw new ServiceException(String.format("获取小程序价格信息失败：%s", JSON.toJSONString(projects)));
        }

        JSONObject projectsJson = new JSONObject(projects);

        JSONObject jsonObject = projectsJson.getJSONObject("data");
        if (jsonObject != null) {
            JSONArray ticketDetails = jsonObject.getJSONArray("ticketDetails");
            if (!ticketDetails.isEmpty()) {
                for (int i = 0; i < ticketDetails.size(); i++) {

                    JSONObject ticketDetail = ticketDetails.getJSONObject(i);
                    JSONArray categories = ticketDetail.getJSONArray("categories");
                    for (int i1 = 0; i1 < categories.size(); i1++) {
                        JSONObject categorie = categories.getJSONObject(i1);
                        BigDecimal miniAppPrice = categorie.getBigDecimal("miniAppPrice");
                        if (miniAppPrice != null) {
                            if (minPrice == null || miniAppPrice.compareTo(minPrice) == -1) {
                                minPrice = miniAppPrice;
                            }

                            if (maxPrice == null || miniAppPrice.compareTo(maxPrice) == 1) {
                                maxPrice = miniAppPrice;
                            }
                        }
                    }
                }
            }
        }

        shopProjectDTO.setMaxPrice(maxPrice.toString());
        shopProjectDTO.setMinPrice(minPrice.toString());

        return shopProjectDTO;
    }

    /**
     * 查询项目
     *
     * @param projectId 项目主键
     * @return 项目
     */
    @Override
    public Project selectProjectByProjectId(Long projectId) {
        return projectMapper.selectProjectByProjectId(projectId);
    }

    /**
     * 查询项目列表
     *
     * @param project 项目
     * @return 项目
     */
    @Override
    public List<Project> selectProjectList(Project project) {
        PageUtils.startPage();
        return projectMapper.selectProjectList(project);
    }

    /**
     * 新增项目
     *
     * @param project 项目
     * @return 结果
     */
    @Override
    public int insertProject(Project project) {
        project.setStatus(0);
        project.setNumber(NumberGenerator.getCharacters());
        project.setCreateTime(DateUtils.getNowDate());
        return projectMapper.insertProject(project);
    }

    /**
     * 修改项目
     *
     * @param project 项目
     * @return 结果
     */
    @Override
    public int updateProject(Project project) {
        project.setUpdateTime(DateUtils.getNowDate());
        return projectMapper.updateProject(project);
    }

    /**
     * 批量删除项目
     *
     * @param projectIds 需要删除的项目主键
     * @return 结果
     */
    @Override
    public int deleteProjectByProjectIds(Long[] projectIds) {
        int total = 0;
        for (Long projectId : projectIds) {
//修复项目已经在门店中引用，但是仍然可以删除

            int num = slkjShopProjectFzMapper.selectShopProjectFz(projectId);
            if (num > 0) {
                return 0;
            }
            total += deleteProjectByProjectId(projectId);

        }
        return total;
    }

    /**
     * 删除项目信息
     *
     * @param projectId 项目主键
     * @return 结果
     */
    @Override
    public int deleteProjectByProjectId(Long projectId) {
        Project project = new Project();
        project.setProjectId(projectId);
        project.setStatus(1);
        project.setUpdateTime(DateUtils.getNowDate());


        int num = slkjShopProjectFzMapper.selectShopProjectFz(projectId);
        if (num > 0) {
            return 0;
        }
        return projectMapper.updateProject(project);
    }

    @Override
    public AjaxResult projectSelected(String projectName) {
        Project project = new Project();
        project.setStatus(0);
        project.setName(projectName);
        List<Project> projects = projectMapper.selectProjectList(project);
        if (CollectionUtils.isEmpty(projects)) {
            return AjaxResult.success(Lists.newArrayList());
        }

        List<Map<String, String>> result = Lists.newArrayList();
        Map<String, String> map;
        for (Project pjt : projects) {
            map = new HashMap<>();
            map.put("projectId", pjt.getProjectId() + "");
            map.put("projectNumber", pjt.getNumber());
            map.put("projectName", pjt.getName());
            map.put("projectEnglishName", pjt.getEnglishName());
            result.add(map);
        }
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult projectDetail(String id) {
        Project project = projectMapper.selectProjectByProjectId(Long.parseLong(id));
        if (project == null) {
            return AjaxResult.error("项目不存在！");
        }

        ProjectDetailVo result = new ProjectDetailVo();
        BeanUtils.copyProperties(project, result);

        SlkjCopyright copyright = slkjCopyrightMapper.selectSlkjCopyrightByCopyrightId(project.getCopyrightId());
        if (copyright != null) {
            result.setCopyrightNumber(copyright.getCopyrightNumber());
            result.setCompanyName(copyright.getCompanyName());
            result.setCreditCode(copyright.getCreditCode());
        }
        return AjaxResult.success(result);
    }

}
